package common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
* @author Omri Barda		039725890
* @author Amit Joseph		034608547
* @author Gilad Shpigel  	300162393
* @author Elad Elbaz		040539959
* @author Natali Kazav		038109401
* @version May 2012
*/

/**
 * Constructs a Database.
 */

public class Database {
	
	private final Connection conn;
	private static final String database = "JDBC:mysql://localhost/aes_prototype";
	private static final String driver = "com.mysql.jdbc.Driver";
	private static final String username = "root";
	private static String password = "123123";

	public Database() throws Exception
	{
	try 
	{
        Class.forName(driver).newInstance();
    } catch (Exception ex) {throw ex;}
    
    try 
    {
        conn = DriverManager.getConnection(database,username,password);          
 	} catch (SQLException ex) 
 	    {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
            throw ex;
        }
	}
	
	/**
	 * Adding question to the Database.
	 *
	 * @param Query for execution.
	 */	
	
	public Boolean addQuestion(String query)
	{
		Statement st;
		try
		{
			st = conn.createStatement();
			st.executeUpdate(query);
			return true;
		} catch (SQLException e) 
			{
				Perror.pError("Unable to create question!"); 
				return false;
			}
	}

	/**
	 * Deleting question from the Database.
	 *
	 * @param Query for execution.
	 */		
	
	public Boolean deleteQuestion(String query)
	{
		Statement st;
		try
		{
			st = conn.createStatement();
			st.executeUpdate(query);
			return true;
		} catch (SQLException e) 
			{
				Perror.pError("Unable to delete question!"); 
				return false;
			}	
	}

	
	/**
	 * Getting question from the Database.
	 *
	 * @param Query for execution.
	 */	
	
	public ResultSet getQuestion(String query)
	{
		Statement st;
		try
		{
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(query);
			return rs;
		} catch (SQLException e) 
			{
				Perror.pError("Unable to get question!"); 
				return null;
			}	
	}
}
